package com.iclient.dao.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.iclient.dao.ext.TreeNode;
import com.iclient.dao.mapper.NavMapper;
import com.iclient.dao.model.Nav;
import com.iclient.dao.service.NavService;

@Service
public class NavServiceImpl implements NavService{

	@Autowired
	private NavMapper navMapper;
	
	@Override
	public List<TreeNode> findNavTree() {
		List<Nav> navs = navMapper.findList();
		TreeNode rootNode = new TreeNode();
		rootNode.setText("菜单");
		rootNode.setChildren(new ArrayList<TreeNode>());
		Map<Integer, List<Nav>> maps = new HashMap<>();
		if(!CollectionUtils.isEmpty(navs)){
			for(Nav nav : navs){
				if(!nav.getModule()){
					if(maps.get(nav.getModuleId()) != null){
						maps.get(nav.getModuleId()).add(nav);
					}else{
						List<Nav> list = new ArrayList<>();
						list.add(nav);
						maps.put(nav.getModuleId(), list);
					}
				}else{
					TreeNode moduleNode = new TreeNode();
					moduleNode.setText(nav.getNavname());
					moduleNode.setAttributes(new HashMap<String, Object>());
					moduleNode.getAttributes().put("id", nav.getId());
					rootNode.getChildren().add(moduleNode);
				}
			}
		}
		for(TreeNode treeNode : rootNode.getChildren()){
			if(maps.get(treeNode.getAttributes().get("id")) != null){
				List<TreeNode> leftNodes = new ArrayList<>();
				for(Nav nav : maps.get(treeNode.getAttributes().get("id"))){
					TreeNode leftNode = new TreeNode();
					leftNode.setText(nav.getNavname());
					leftNode.setAttributes(new HashMap<String, Object>());
					leftNode.getAttributes().put("url", nav.getUrl());
					leftNodes.add(leftNode);
				}
				treeNode.setChildren(leftNodes);
			}
		}
		return rootNode.getChildren();
	}

}
